package com.itttq.gen.common.ext;

import com.itttq.gen.common.constant.Constants;
import com.itttq.gen.model.to.ResultTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class AuthIntercept implements HandlerInterceptor {
    /**
     * 此处写自己的判断逻辑。可以进行Session或Token的拦截验证
     * 也可以进行权限验证。如果拦截通过则返回true；反之返回false
     *
     * @return true则继续往下执行；false则不会继续往下执行
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 判断Session是否过期
        if (!checkLogin(request, response)) {
            return false;
        }
        return true;
    }

    /**
     * 验证用户是否有效
     *
     * @return
     */
    private boolean checkLogin(HttpServletRequest request, HttpServletResponse response) {
        Object account = request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
        boolean rs = null != account;
        if (rs) {
            return true;
        }
        PrintWriter writer = null;
        try {
            response.setContentType("application/json; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            writer = response.getWriter();
            writer.write("{\"code\":" + ResultTo.ResultCode.SESSION_INVALID.getCode() + ",\"msg\":\"请重新登录\"}");
            writer.flush();
        } catch (IOException e) {
            log.error("response write err", e);
        } finally {
            if (null != writer) {
                writer.close();
            }
        }
        return false;
    }
}
